package com.mofeng.myshop.until;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;


public class ServletUtils {
    /**
     * 获取request
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getRequest();
    }

    /**
     * 获取response
     *
     * @return
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getResponse();
    }

    public static String getUserIp() {
        return getRequest().getRemoteAddr();
//        return getRequest().getHeader("X-Forwarded-For");
    }

    public static List<String> parseDomain(String domain) {
        try {
            // 获取域名的所有 IP 地址
            List<String> result = new ArrayList<>();
            InetAddress[] inetAddresses = InetAddress.getAllByName(domain);
            for (InetAddress inetAddress : inetAddresses) {
//                System.out.println("IP 地址: " + inetAddress.getHostAddress());
                result.add(inetAddress.getHostAddress());
            }
            return result;
        } catch (UnknownHostException e) {
            System.err.println("无法解析域名: " + domain);
            e.printStackTrace();
            throw new RuntimeException("无法解析域名",e);
        }
    }
}
